package com.xp.basic.heima.nio.netty.simpledemo.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.charset.StandardCharsets;

/**
 * 粘包测试
 */
public class TestStickyWrap {

    public static void main(String[] args) {
        EmbeddedChannel embeddedChannel = new EmbeddedChannel();

        //解决粘包和半包问题   LTC 解码器  定长解码器  行解码器
        LengthFieldBasedFrameDecoder decoder = new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4);
        embeddedChannel.pipeline().addLast(new LoggingHandler());
        embeddedChannel.pipeline().addLast(decoder);
        embeddedChannel.pipeline().addLast(new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                System.out.println(" 通道 init ");
            }

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                System.out.println("通道建立");
                super.channelActive(ctx);
            }

            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                System.out.println("接受到管道中的对象为："+ msg.toString());
                super.channelRead(ctx, msg);
            }
        });

        byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8);
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        buffer.writeInt(bytes.length);
        buffer.writeBytes(bytes);

        embeddedChannel.writeInbound(buffer);
    }
}
